package br.com.maiscontrole.view.site.beans.abst;

import java.text.MessageFormat;
import java.util.Collection;
import java.util.Map;
import java.util.ResourceBundle;

import javax.faces.application.FacesMessage;
import javax.faces.application.FacesMessage.Severity;
import javax.faces.bean.ManagedProperty;
import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;

import br.com.base.exception.BaseException;
import br.com.maiscontrole.exception.NegociosMaisControleException;
import br.com.maiscontrole.facade.Facade;

/**
 * 
 * @author milton
 *
 * @param <ENTITY>
 */
public abstract class AbstractMB {

	private String MAIS_CONTROLE = "maiscontrole";

	@ManagedProperty("#{facade}")
	private Facade facade;

	private String acao;

	public AbstractMB() {

	}

	public void adicionarMensagem(Severity severity, String sumario, String detalhes){
		FacesContext context = FacesContext.getCurrentInstance();
		FacesMessage message = new FacesMessage(severity, sumario, detalhes);
		context.addMessage(null, message);
	}

	public String getAcao() {
		return this.acao;
	}

	@SuppressWarnings("unchecked")
	protected <T extends AbstractMB> T getBeanMB(String beanName,  Class<T> beanClazz) {
		T bean = null;
		FacesContext currentInstance = FacesContext.getCurrentInstance();
		if (currentInstance != null) {
			Map<String, Object> sessionMap = currentInstance.getExternalContext().getSessionMap();
			bean = (T) sessionMap.get(beanName);
			if (bean == null) {
				try {
					bean = beanClazz.newInstance();
					sessionMap.put(beanName, bean);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		return bean;
	}

	private String getExceptionCauseMsg(Exception exception) {
		String cause = "";
		if((exception.getCause() != null) && (exception.getCause().getMessage() != null)) {
			cause = exception.getCause().getMessage();
		}
		return cause;
	}

	public Facade getFacade() {
		return this.facade;
	}

	protected String getMensagemBuddle(String key, Object... params){
		UIViewRoot view = FacesContext.getCurrentInstance().getViewRoot();
		String mensagemBuddle = ResourceBundle.getBundle(this.MAIS_CONTROLE, view.getLocale()).getString(key);
		String mensagemFormatada = MessageFormat.format(mensagemBuddle, params);
		return mensagemFormatada;
	}

	public void setAcao(String acao) {
		this.acao = acao;
	}

	public abstract void setarDados();

	public void setFacade(Facade facade) {
		this.facade = facade;
	}

	protected void tratarExcecoes(Exception exception) {

		if (exception instanceof NegociosMaisControleException) {
			Collection<BaseException> negocios = ((NegociosMaisControleException)exception).getErros();
			if(negocios != null) {
				for (BaseException base : negocios) {
					this.verificarExceptionAddMsg(base);
				}
			} else {
				this.verificarExceptionAddMsg((BaseException) exception);
			}
		} else {
			this.adicionarMensagem(FacesMessage.SEVERITY_ERROR, exception.getMessage(), this.getExceptionCauseMsg(exception));
		}

	}

	private void verificarExceptionAddMsg(BaseException base){
		if(base instanceof NegociosMaisControleException){
			NegociosMaisControleException negociosException = (NegociosMaisControleException) base;
			String mensagem = this.getMensagemBuddle(negociosException.getMessage(),negociosException.getParams());
			this.adicionarMensagem(FacesMessage.SEVERITY_ERROR, mensagem, this.getExceptionCauseMsg(base));
		}else{
			this.adicionarMensagem(FacesMessage.SEVERITY_ERROR, base.getMessage(), this.getExceptionCauseMsg(base));
		}

	}

}
